#!/bin/bash

# 配置参数
REMOTE_IP="10.83.4.34"
REMOTE_PORT="10022"
SFTP_USER="appcheck"
SFTP_PASS="q1w2E#R\$"
REMOTE_PATH="/share/share2/fadap"
LOCAL_PATH="/home/app"
LOG_FILE="info.log"

# 检查expect是否安装
if ! command -v expect &> /dev/null; then
    echo "[ERROR] expect command not found. Please install expect first." | tee -a $LOG_FILE
    exit 1
fi

# 检查本地文件是否存在
if [ ! -d "$LOCAL_PATH" ]; then
    echo "[ERROR] Local directory $LOCAL_PATH does not exist" | tee -a $LOG_FILE
    exit 1
fi

# 获取当前时间
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")

# 开始上传
echo "[$TIMESTAMP] Starting SFTP upload to $REMOTE_IP:$REMOTE_PORT" | tee -a $LOG_FILE

# 使用expect自动处理SFTP交互
/usr/bin/expect <<- EOF
    set timeout 300
    spawn sftp -oPort=$REMOTE_PORT $SFTP_USER@$REMOTE_IP
    expect {
        "*yes/no*" { 
            send "yes\r"
            expect "*assword*" 
            send "$SFTP_PASS\r" 
        }
        "*assword*" { 
            send "$SFTP_PASS\r" 
            expect {
                "Permission denied" {
                    puts "\n[$TIMESTAMP] Authentication failed - incorrect password" | tee -a $LOG_FILE
                    exit 1
                }
                "sftp>" 
            }
        }
        timeout {
            puts "\n[$TIMESTAMP] Connection timeout to $REMOTE_IP:$REMOTE_PORT" | tee -a $LOG_FILE
            exit 1
        }
        eof {
            puts "\n[$TIMESTAMP] Connection failed to $REMOTE_IP:$REMOTE_PORT" | tee -a $LOG_FILE
            exit 1
        }
    }
    expect "sftp>"
    send "cd $REMOTE_PATH\r"
    expect "sftp>"
    send "lcd $LOCAL_PATH\r"
    expect "sftp>"
    send "put -r ./*\r"
    expect "sftp>"
    send "bye\r"
    expect eof
EOF

# 检查上传结果
if [ $? -eq 0 ]; then
    echo "[$TIMESTAMP] Upload completed successfully" | tee -a $LOG_FILE
    exit 0
else
    echo "[$TIMESTAMP] Upload failed" | tee -a $LOG_FILE
    exit 1
fi
